package office.document.docx4j.utils;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.spire.doc.Document;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import office.CustomConstant;
import office.document.pdfbox.SpireServiceLimit;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Objects;

/**
 * word合并
 *
 * @author: 张卢
 * @date: 2023/8/1 20:55
 * @modify: 修改人信息, 修改内容 修改时间 2023/8/1 20:55
 * @Version: 1.0.0 类版本
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class WordMergeUtil {

    /**
     * WORD文档合并（每个word最多3页，文档总个数最多{@link CustomConstant#WORD_MERGE_SUB_FILE_MAX_COUNT}页）
     *
     * @param bytes docx格式字节数组列表
     * @return 合并后的docx格式字节数组
     */
    public static byte[] mergeWords(List<byte[]> bytes) {
        if (ObjectUtil.isEmpty(bytes)) {
            return new byte[0];
        }
        Assert.isTrue(bytes.size() <= CustomConstant.WORD_MERGE_SUB_FILE_MAX_COUNT, () -> new RuntimeException(CharSequenceUtil.format(CustomConstant.WORD_MERGE_SUB_FILE_LIMIT_TIP, CustomConstant.WORD_MERGE_SUB_FILE_MAX_COUNT)));
        //创建 Document 类的对象并从磁盘加载 Word 文档
        Document document = new Document();
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            for (int i = 0; i < bytes.size(); i++) {
                byte[] bs = bytes.get(i);
                if(Objects.equals(0, bs.length)){
                    continue;
                }
                //子文件合并
                SpireServiceLimit.pdfConvertAndWordMerge(() -> null, () -> {
                    document.insertTextFromStream(new ByteArrayInputStream(bs), com.spire.doc.FileFormat.Docx);
                    return null;
                });
            }
            //输出合并后的word文件
            document.saveToStream(out, com.spire.doc.FileFormat.Docx);
            return out.toByteArray();
        } catch (Exception e) {
            log.error("合并word异常", e);
        } finally {
            try {
                document.close();
            } catch (Exception e) {
                log.error("合并word，关闭流异常", e);
            }
        }
        return new byte[0];
    }

}
